package com.egao.common.article.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.egao.common.article.entity.TArticle;
import com.egao.common.article.entity.TArticleType;
import com.egao.common.article.entity.dto.ArticleDto;
import com.egao.common.article.service.ITArticleService;
import com.egao.common.article.service.ITArticleTypeService;
import com.egao.common.article.service.impl.TArticleServiceImpl;
import com.egao.common.core.utils.FileUploadUtil;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.system.entity.User;
import com.egao.common.system.entity.UserTwo;
import com.egao.common.system.service.UserService;
import com.egao.common.system.service.UserTwoService;
import com.egao.common.test.entity.Release;
import com.egao.common.test.service.MenurService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @auther ZhaoPeng Wang
 * @create 2022-03-18 10:42:25
 * @description 文章表前端控制器
 */
@Controller
@RequestMapping("/article")
@Slf4j
public class TArticleController {
    @Autowired
    MenurService menurService;

    @Autowired
    ITArticleService itArticleService;

    @Autowired
    UserService userService;

    @Autowired
    UserTwoService userTwoService;

    @Autowired
    ITArticleTypeService itArticleTypeService;


        @RequestMapping()
        public String view(Model model) {
            model.addAttribute("typeList", itArticleTypeService.list());
            model.addAttribute("articleList", itArticleService.list());
            return "course/article-manage.html";
        }

    /**
     * 分页查询
     */
    @ResponseBody
    @RequestMapping("/page")
    public PageResult<TArticle> page(HttpServletRequest request) {
        PageParam<TArticle> pageParam = new PageParam<>(request);
        return new PageResult<>(itArticleService.page(pageParam, pageParam.getWrapper()).getRecords(), pageParam.getTotal());
        //return classifyService.listPage(pageParam);  // 使用关联查询
    }

    /**
     * 按类型分页查询
     */
    @ResponseBody
    @RequestMapping("/pageByType")
    public PageResult<TArticle> pageByType(HttpServletRequest request) {
        PageParam<TArticle> pageParam = new PageParam<>(request);
        return new PageResult<>(itArticleService.page(pageParam, pageParam.getWrapper()).getRecords(), pageParam.getTotal());
        //return classifyService.listPage(pageParam);  // 使用关联查询
    }

    /**
     * 查询全部
     */
    @ResponseBody
    @RequestMapping("/list")
    public JsonResult list(HttpServletRequest request) {
        PageParam<TArticle> pageParam = new PageParam<>(request);
        return JsonResult.ok().setData(itArticleService.list(pageParam.getOrderWrapper()));
        //List<Classify> records = classifyService.listAll(pageParam.getNoPageParam());  // 使用关联查询
        //return JsonResult.ok().setData(pageParam.sortRecords(records));
    }

    /**
     * 根据id查询
     */
    @ResponseBody
    @RequestMapping("/get")
    public JsonResult get(Integer id) {
        return JsonResult.ok().setData(itArticleService.getById(id));
    }

    /**
     * 根据id查询
     */
    @ResponseBody
    @RequestMapping("/getNameById")
    public String getNameById(Integer id) {
        log.info("类型ID为: {}",id);
        TArticle byId = itArticleService.getById(id);
        log.info("类型为: {}",byId.toString());
        return byId.getName();
    }

    /**
     * 审核
     * @param id
     * @param state
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping("/shenhe")
    public JsonResult ShenHe(Integer id,Integer state,Integer userId) {
        TArticle article = itArticleService.getById(id);
        UserTwo usertwo = userTwoService.getById(userId);
        article.setState(state);
        if (itArticleService.updateById(article)) {
           return JsonResult.ok("添加成功");
        }
        return JsonResult.error("添加失败");
    }

    /**
     * 添加
     */
    @ResponseBody
    @RequestMapping("/save")
    public JsonResult save(ArticleDto articleDto) {
        TArticle article = new TArticle();
        BeanUtils.copyProperties(articleDto,article);

        Subject subject = SecurityUtils.getSubject();
        Object object = subject.getPrincipal();
        Integer userId;
        try {
             userId = ((UserTwo) object).getUserId();
        }catch (ClassCastException e){
            userId = 0;

        }
        article.setUserId(userId);
        article.setDelFlag(0);
        article.setCreateTime(new Date());
        article.setState(0);
        if (itArticleService.save(article)) {
            return JsonResult.ok("添加成功");
        }
        return JsonResult.error("添加失败");
    }


    /**
     * 保存文章
     * @param name
     * @param content
     * @param image
     * @return
     */
    @PostMapping("/articleSave")
    @ResponseBody
    public JsonResult releaseSave(String name, String content, String image,Integer type) {
        Subject subject = SecurityUtils.getSubject();
        Object object = subject.getPrincipal();
        if (object != null) {
            TArticle article = new TArticle();
            article.setName(name);
            article.setCreateTime(new Date());
            article.setDelFlag(0);
            article.setType(type);
            article.setContent(content);
            article.setState(0);
            article.setId(((UserTwo)object).getUserId());
            article.setImage(image);
            Boolean res = itArticleService.save(article);
            if(res) {
                return JsonResult.ok("保存成功");
            }else {
                return JsonResult.error("保存失败");
            }
        } else {
            return JsonResult.error("请先登录");
        }
    }

    /**
     * 删除文章
     * @param id
     * @return
     */
    @RequestMapping("/deleteArticle")
    public JsonResult deleteArticle(Integer id) {
        if (itArticleService.removeById(id)) {
            return JsonResult.ok("删除成功");
        }
        return JsonResult.error("删除失败");
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    public JsonResult update(ArticleDto articleDto) {
        TArticle article = new TArticle();
        BeanUtils.copyProperties(articleDto,article);
        if (itArticleService.updateById(article)) {
            return JsonResult.ok("修改成功");
        }
        return JsonResult.error("修改失败");
    }

    /**
     * 批量删除
     */
    @ResponseBody
    @RequestMapping("/removeBatch")
    public JsonResult removeBatch(@RequestBody List<Integer> ids) {
        if (itArticleService.removeByIds(ids)) {
            return JsonResult.ok("删除成功");
        }
        return JsonResult.error("删除失败");
    }

    /**
     * 加载图片
     * @param file
     * @return
     */
    @ResponseBody
    @PostMapping("/edit_upload")
    public JsonResult edit_upload(@RequestParam MultipartFile file) {
        return FileUploadUtil.edit_upload(file);
    }

    /**
     * 将图片放置指定位置并返回路径
     * @param file
     * @return
     */
    @ResponseBody
    @PostMapping("/upload")
    public JsonResult upload(@RequestParam MultipartFile file) {
        return FileUploadUtil.upload(file);
    }

}

